package org.yidu.spider.security;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.CollectionUtils;
import org.yidu.spider.entity.UserInfo;
import org.yidu.spider.repository.UserInfoRepository;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/regedit", "/css/**", "/js/**", "/webjars/**").permitAll().anyRequest()
                .authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll()
                .deleteCookies("JSESSIONID").invalidateHttpSession(true).permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(username -> {
            List<UserInfo> userList = userInfoRepository.findByUserName(username);
            if (!CollectionUtils.isEmpty(userList)) {
                return new User(userList.get(0).getUserName(), userList.get(0).getPassword(), Collections
                        .singleton(new SimpleGrantedAuthority("USER")));
            } else {
                throw new UsernameNotFoundException("Invalid username");
            }
        });
    }
}
